import Cookies from "js-cookie";
import { useUserStoreHook } from "@/store/modules/user";
import { storageLocal, isString, isIncludeAllChildren } from "@pureadmin/utils";
import { getConfig } from "@/config";

export interface DataInfo {
  /** 头像 */
  avatar?: string;
  /** 账户名 */
  accountName: string;
  /** 姓名 */
  realName?: string;
  /** 所属租户ID */
  tenantId: string;
  /** 所属租户名称 */
  tenantName: string;
  /** 账户类型 0-普通账户，1-管理员 */
  accountType: number;
  /** 当前登录用户的角色 */
  roles?: Array<string>;
}

export const userKey = "user-info";
export const sessionTimeoutKey = "session-time";
/**
 * 通过`multiple-tabs`是否在`cookie`中，判断用户是否已经登录系统，
 * 从而支持多标签页打开已经登录的系统后无需再登录。
 * 浏览器完全关闭后`multiple-tabs`将自动从`cookie`中销毁，
 * 再次打开浏览器需要重新登录系统
 * */
export const multipleTabsKey = "multiple-tabs";

export function refreshSessionTimeout() {
  storageLocal().setItem(sessionTimeoutKey, new Date().getTime() );
}
export function isSessionTimeout(): boolean {
  const currentTime = new Date().getTime();
  const sessionTimeout = 1000 * 60 * getConfig().sessionTimeout;
  return (currentTime - getSessionTimeout() > sessionTimeout);
}
function getSessionTimeout(): number {
  const timeout: number = storageLocal().getItem(sessionTimeoutKey) ?? -1;

  return timeout;
}

/** 获取本地账户信息 */
export function getAccount(): DataInfo {
  return storageLocal().getItem(userKey);
}

/**
 * @description 设置账户信息
 */
export function setAccount(data: DataInfo) {
  const { isRemembered, loginDay } = useUserStoreHook();
  Cookies.set(
    multipleTabsKey,
    "true",
    isRemembered
      ? {
        expires: loginDay
      }
      : {}
  );

  function setUserKey({
    avatar,
    accountName,
    realName,
    accountType,
    tenantId,
    tenantName,
    roles
  }) {
    useUserStoreHook().SET_AVATAR(avatar);
    useUserStoreHook().SET_ACCOUNTNAME(accountName);
    useUserStoreHook().SET_REALNAME(realName);
    useUserStoreHook().SET_ACCOUNTTYPE(accountType);
    useUserStoreHook().SET_TENANTID(tenantId);
    useUserStoreHook().SET_TENANTNAME(tenantName);
    roles = [accountType == 1 ? "admin" : "common"];
    useUserStoreHook().SET_ROLES(roles);
    storageLocal().setItem(userKey, {
      accountName,
      realName,
      avatar,
      accountType,
      tenantId,
      tenantName,
      roles
    });
  }

  if (data.accountName) {
    const { accountName } = data;
    setUserKey({
      avatar: data?.avatar ?? "",
      accountName,
      realName: data?.realName ?? "",
      tenantId: data?.tenantId ?? "",
      tenantName: data?.tenantName ?? "",
      accountType: data?.accountType ?? 0,
      roles: data?.roles ?? ["common"]
    });
  } else {
    const avatar = storageLocal().getItem<DataInfo>(userKey)?.avatar ?? "";
    const accountName =
      storageLocal().getItem<DataInfo>(userKey)?.accountName ?? "";
    const realName = storageLocal().getItem<DataInfo>(userKey)?.realName ?? "";
    const accountType =
      storageLocal().getItem<DataInfo>(userKey)?.accountType ?? 0;
    const tenantId = storageLocal().getItem<DataInfo>(userKey)?.tenantId ?? "";
    const tenantName =
      storageLocal().getItem<DataInfo>(userKey)?.tenantName ?? "";
    const roles = storageLocal().getItem<DataInfo>(userKey) ?? ["common"];
    setUserKey({
      avatar,
      accountName,
      realName,
      accountType,
      tenantId,
      tenantName,
      roles
    });
  }
  refreshSessionTimeout();
}

/** 删除key值为`user-info`的localStorage信息 */
export function removeAccount() {
  Cookies.remove(multipleTabsKey);
  storageLocal().removeItem(userKey);
}

/** 是否有按钮级别的权限（根据登录接口返回的`permissions`字段进行判断）*/
export const hasPerms = (value: string | Array<string>): boolean => {
  // if (!value) return false;
  // const allPerms = "*:*:*";
  // const { permissions } = useUserStoreHook();
  // if (!permissions) return false;
  // if (permissions.length === 1 && permissions[0] === allPerms) return true;
  // const isAuths = isString(value)
  //   ? permissions.includes(value)
  //   : isIncludeAllChildren(value, permissions);
  // return isAuths ? true : false;
  return true;
};
